﻿using System;
using System.Windows.Forms;
using System.Net;
using monitor_2_DBwork;

namespace monitor_server_2
{
    public partial class AddTrustedAddress : Form
    {
        readonly GetAllRegDelegate _regions;
        readonly GetSelRegDelegate _selRegion;
        readonly TreeUpdateDelegate _updateTree;

        public AddTrustedAddress(GetAllRegDelegate sender1, GetSelRegDelegate sender2, TreeUpdateDelegate sender3)
        {
            InitializeComponent();
            _regions = sender1;
            _selRegion = sender2;
            _updateTree = sender3;
        }

        private void AddMenuForm_Load(object sender, EventArgs e)
        {
            Text = Main.Rm.GetString("AddNewTrustedAddress");
            oblLabel.Text = Main.Rm.GetString("Region");
            ipLabel.Text = Main.Rm.GetString("IPAddress");
            addButAccept.Text = Main.Rm.GetString("Accept");
            addButCancel.Text = Main.Rm.GetString("Cancel");
            oblComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            oblComboBox.Items.AddRange(_regions()); 
            oblComboBox.SelectedItem = _selRegion();                       
        }

        private void addButCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void addButAccept_Click(object sender, EventArgs e)
        {
            IPAddress ip;
            if (!IPAddress.TryParse(ipTextBox.Text, out ip))
                MessageBox.Show(Main.Rm.GetString("WrongParameter") + @": " + Main.Rm.GetString("IPAddress"));

            try
            {
                DBwork.AddTrustedAddress(IPAddress.Parse(ipTextBox.Text).ToString(), oblComboBox.SelectedItem.ToString());
            }
            catch (FormatException ex)
            {
                if (ex.Message == "Указан недопустимый адрес IP.")
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            Close();
        }

        private void AddMenuForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _updateTree();
        }
    }
}
